package com.ikingtech.platform.service.push.websocket.cluster;

import com.ikingtech.framework.sdk.cluster.node.handler.ClusterNodeMessageHandler;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.push.common.PushRequest;
import com.ikingtech.platform.service.push.websocket.WebsocketClusterDeliver;
import com.ikingtech.platform.service.push.websocket.session.WebsocketSessionManager;
import io.netty.buffer.ByteBuf;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class ClusterNodeWebsocketPushNotifyMessageHandler implements ClusterNodeMessageHandler {

    private final WebsocketClusterDeliver deliver;

    @Override
    public void handle(Object message) {
        ClusterNodeWebsocketPushNotifyMessage notifyMessage = Tools.Json.toBean(((ByteBuf) message).toString(Charset.defaultCharset()), ClusterNodeWebsocketPushNotifyMessage.class);
        if (null == notifyMessage) {
            log.warn("[CLUSTER]websocket push notify message is null");
            return;
        }
        List<WebSocketSession> sessions = WebsocketSessionManager.get(notifyMessage.getReceiverId());
        if (Tools.Coll.isBlank(sessions)) {
            return;
        }
        PushRequest pushRequest = new PushRequest();
        pushRequest.setBody(notifyMessage.getMessageBody());
        this.deliver.execute(sessions, pushRequest);
    }
}
